package com.zxx.casserver.modules.oplog.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.zxx.casserver.modules.oplog.entity.OpLogDO;
import com.zxx.casserver.modules.oplog.entity.OpLogVO;
import com.zxx.casserver.modules.oplog.mapper.OpLogMapper;
import com.zxx.casserver.modules.oplog.service.IOpLogService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 * 系统操作日志表 服务实现类
 * </p>
 *
 * @author zhoukai
 * @since 2020-08-03
 */
@Service
public class OpLogServiceImpl extends ServiceImpl<OpLogMapper, OpLogDO> implements IOpLogService {

    @Override
    public IPage<OpLogDO> listOpLog(OpLogVO opLogVO) {
        Page<OpLogDO> page = new Page<>(opLogVO.getCurPage(), opLogVO.getPageSize());
        QueryWrapper<OpLogDO> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(opLogVO.getIds())) {
            queryWrapper.in("id", opLogVO.getId());
        }
        if (!ObjectUtils.isEmpty(opLogVO.getUid())) {
            queryWrapper.eq("uid", opLogVO.getUid());
        }

        if (!ObjectUtils.isEmpty(opLogVO.getModules())) {
            queryWrapper.eq("modules", opLogVO.getModules());
        }
        if (!ObjectUtils.isEmpty(opLogVO.getAction())) {
            queryWrapper.eq("action", opLogVO.getAction());
        }
        if (!ObjectUtils.isEmpty(opLogVO.getStartTime())) {
            queryWrapper.ge("op_time", opLogVO.getStartTime());
        }
        if (!ObjectUtils.isEmpty(opLogVO.getEndTime())) {
            queryWrapper.le("op_time", opLogVO.getEndTime());
        }
        if (!ObjectUtils.isEmpty(opLogVO.getColumns()) && !ObjectUtils.isEmpty(opLogVO.getAsc())) {
            String columnNames = Joiner.on(",").join(opLogVO.getColumns());
            if (opLogVO.getAsc()) {
                queryWrapper.orderByAsc(columnNames);
            } else {
                queryWrapper.orderByDesc(columnNames);
            }
        } else {
            queryWrapper.orderByDesc("op_time");
        }
        return page(page, queryWrapper);
    }

    @Override
    public OpLogDO saveOpLog(OpLogVO opLogVO) {
        OpLogDO opLogDO = JSON.parseObject(JSON.toJSONString(opLogVO), OpLogDO.class);
        opLogDO.setOpTime(System.currentTimeMillis());
        boolean isSave = save(opLogDO);
        if (isSave) {
            return getById(opLogDO.getId());
        }
        return null;
    }
}
